"""
相机MCP服务器实现
获取相机视频画面、图像数据
"""

from typing import Dict, Any, Optional
from mcp.server.fastmcp import FastMCP
from sensors.camera_sensor import CameraSensor
from config.sensor_config import CAMERA_SENSOR_CONFIG
import cv2
import numpy as np
import base64
import time


class CameraServer(FastMCP):
    """相机服务器类"""

    def __init__(self):
        """初始化相机服务器"""
        super().__init__("camera_server")

        # 初始化相机传感器
        self.sensor = CameraSensor(CAMERA_SENSOR_CONFIG)

        # 注册工具
        self._register_tools()

    def _register_tools(self):
        """注册所有相机工具"""

        @self.tool()
        async def get_frame() -> Dict[str, Any]:
            """获取当前帧图像

            Returns:
                Dict[str, Any]: 图像数据
            """
            try:
                frame = await self.sensor.get_frame()
                if frame is not None:
                    # 将图像转换为base64编码
                    _, buffer = cv2.imencode(".jpg", frame)
                    image_base64 = base64.b64encode(buffer).decode("utf-8")

                    return {
                        "status": "success",
                        "data": {
                            "image": image_base64,
                            "width": frame.shape[1],
                            "height": frame.shape[0],
                            "channels": frame.shape[2],
                            "timestamp": time.time(),
                        },
                    }
                else:
                    return {"status": "error", "message": "Failed to get frame"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def get_frame_base64() -> Dict[str, Any]:
            """获取当前帧的base64编码

            Returns:
                Dict[str, Any]: base64编码的图像数据
            """
            try:
                frame_base64 = await self.sensor.get_frame_base64()
                if frame_base64:
                    return {
                        "status": "success",
                        "data": {"image": frame_base64, "timestamp": time.time()},
                    }
                else:
                    return {"status": "error", "message": "Failed to get frame"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def get_sensor_data() -> Dict[str, Any]:
            """获取传感器数据

            Returns:
                Dict[str, Any]: 传感器数据
            """
            try:
                data = await self.sensor.get_sensor_data()
                if "error" in data:
                    return {"status": "error", "message": data["error"]}
                else:
                    return {"status": "success", "data": data}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def set_camera_parameters(
            width: Optional[int] = None,
            height: Optional[int] = None,
            fps: Optional[int] = None,
            exposure: Optional[int] = None,
            gain: Optional[int] = None,
        ) -> Dict[str, Any]:
            """设置相机参数

            Args:
                width: 图像宽度
                height: 图像高度
                fps: 帧率
                exposure: 曝光值
                gain: 增益值

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                if self.sensor.cap is None:
                    return {"status": "error", "message": "Camera not initialized"}

                if width is not None:
                    self.sensor.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
                if height is not None:
                    self.sensor.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
                if fps is not None:
                    self.sensor.cap.set(cv2.CAP_PROP_FPS, fps)
                if exposure is not None:
                    self.sensor.cap.set(cv2.CAP_PROP_EXPOSURE, exposure)
                if gain is not None:
                    self.sensor.cap.set(cv2.CAP_PROP_GAIN, gain)

                return {"status": "success", "message": "Camera parameters updated"}
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def get_camera_parameters() -> Dict[str, Any]:
            """获取相机参数

            Returns:
                Dict[str, Any]: 相机参数
            """
            try:
                if self.sensor.cap is None:
                    return {"status": "error", "message": "Camera not initialized"}

                return {
                    "status": "success",
                    "data": {
                        "width": self.sensor.cap.get(cv2.CAP_PROP_FRAME_WIDTH),
                        "height": self.sensor.cap.get(cv2.CAP_PROP_FRAME_HEIGHT),
                        "fps": self.sensor.cap.get(cv2.CAP_PROP_FPS),
                        "exposure": self.sensor.cap.get(cv2.CAP_PROP_EXPOSURE),
                        "gain": self.sensor.cap.get(cv2.CAP_PROP_GAIN),
                    },
                }
            except Exception as e:
                return {"status": "error", "message": str(e)}

        @self.tool()
        async def restart_camera() -> Dict[str, Any]:
            """重启相机

            Returns:
                Dict[str, Any]: 执行结果
            """
            try:
                await self.sensor.close()
                self.sensor._init_camera()
                return {"status": "success", "message": "Camera restarted"}
            except Exception as e:
                return {"status": "error", "message": str(e)}
